/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ret;
        if(root == nullptr)
            return ret;
        queue<TreeNode*> q;
        q.push(root);
        bool flag = false;
        while(!q.empty())
        {
            int sz = q.size();
            vector<int> tmp(sz); // 统计本层结点
            for(int i = 0; i < sz; ++i)
            {
                TreeNode* t = q.front();
                q.pop();
                tmp[i] = t->val;
                // 下层孩子结点入队
                if(t->left != nullptr)
                    q.push(t->left);
                if(t->right != nullptr)
                    q.push(t->right);
            }
            if(flag)
                reverse(tmp.begin(), tmp.end());
            ret.push_back(tmp);
            flag = flag == false ? true : false;
        }
        return ret;
    }
};